package com.cn.onetrip.activity;

import java.util.ArrayList;
import java.util.List;

import com.cn.onetrip.objects.LarkObj;
import com.cn.onetrip.activity.R;
import com.cn.onetrip.untility.SyncImageLoader;
import com.cn.onetrip.untility.SyncImageLoader.OnImageLoadListener;
import com.cn.onetrip.untility.ImageUtils;
import com.cn.onetrip.untility.SysApplication;
import com.cn.onetrip.untility.Untility;
import com.cn.onetrip.view.AdView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData.Item;
import android.content.res.ColorStateList;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.text.style.BulletSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class PlayViewPagerActivity extends Activity {

	public static final String TAG = "test";
	public ViewPager viewpager = null;
	public List<View> list = null;
	public TextView textView;
	// public static View view;
	private Button quit;
	private int mCount = 2;
	public int textViewId = 9000;
	public int buttonId = 9500;
	private List<LarkObj> larkList;
	private ViewPagerAdapter adapter;
	private int delItem = -1;
	private ArrayList<Integer> arrayDelItem = new ArrayList<Integer>();

	private SyncImageLoader syncImageLoader;
	private AdView adView;

	private int rectWidth, rectHeight;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (SysApplication.larkList.size() == 0) {
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		}
		setContentView(R.layout.activity_viewpager);
		// Window w = getWindow();
		// view = w.getDecorView();
		larkList = SysApplication.larkList;

		viewpager = (ViewPager) findViewById(R.id.viewpager);
		adView = (AdView) findViewById(R.id.ad_view);
		syncImageLoader = new SyncImageLoader(PlayViewPagerActivity.this);
		quit = (Button) findViewById(R.id.quit);
		quit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
				overridePendingTransition(R.anim.push_left_translate,
						R.anim.pull_right_translate);
			}
		});
		if (larkList.size() <= 0) {
			return;
		}

		list = new ArrayList<View>();

		loadDataViewPager();

		LinearLayout layout = (LinearLayout) findViewById(R.id.viewGroup);
		LinearLayout.LayoutParams searchParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		searchParams.leftMargin = 10;
		textView = new TextView(PlayViewPagerActivity.this);
		textView.setText(1 + " / " + list.size());
		layout.addView(textView, searchParams);
		adapter = new ViewPagerAdapter(list);
		viewpager.setAdapter(adapter);
		viewpager.setOnPageChangeListener(new ViewPagerPageChangeListener());

		int lark_id = -1;
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();

		if (bundle != null) {
			lark_id = bundle.getInt("lark_id");
			for (int i = 0; i < larkList.size(); i++) {
				if (lark_id == larkList.get(i).lark_id) {
					viewpager.setCurrentItem(i);
					break;
				}
			}
		}

	}

	@Override
	protected void onResume() {
		adView.startTimer();
		super.onResume();
	}

	@Override
	protected void onPause() {
		syncImageLoader.threadQuit();
		adView.stopTimer();
		super.onPause();
	}

	private void loadDataViewPager() {
		int tvId = textViewId;
		int btnId = buttonId;
		for (int i = 0; i < larkList.size(); i++) {
			final LarkObj larkObj = larkList.get(i);
			final View view = getLayoutInflater().inflate(R.layout.tab1, null);
			RelativeLayout layout = (RelativeLayout) view
					.findViewById(R.id.relativeLayoutPlayContent);
			layout.setId(larkObj.lark_id);
			// layout.setOnLongClickListener(new LayoutLongClick());
			final ImageView iv = (ImageView) view.findViewById(R.id.PlayImage);
			iv.setAdjustViewBounds(true);
			syncImageLoader.loadImage(larkObj.lark_icon,
					new OnImageLoadListener() {

						@Override
						public void onImageLoad(final Drawable drawable) {
							if (drawable != null) {
								iv.setBackgroundDrawable(drawable);
								ViewTreeObserver vto2 = iv
										.getViewTreeObserver();
								vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
									@Override
									public void onGlobalLayout() {
										iv.getViewTreeObserver()
												.removeGlobalOnLayoutListener(
														this);
										rectWidth = iv.getWidth();
										rectHeight = iv.getHeight();
										float scale = (float) rectWidth
												/ rectHeight;
										Bitmap bmp = ImageUtils
												.drawableToBitmap(drawable);
										Bitmap.Config config = Bitmap.Config.RGB_565;
										float w = bmp.getWidth();
										float h = bmp.getHeight();
										Rect r = null;
										if (w / h < scale) {
											int top = (int) (h - (rectHeight
													* w / rectWidth)) / 2;
											r = new Rect(0, top,
													bmp.getWidth(), bmp
															.getHeight() - top);
										} else {
											int left = (int) (w - (rectWidth
													* h / rectHeight)) / 2;
											r = new Rect(left, 0, bmp
													.getWidth() - left, bmp
													.getHeight());
										}
										bmp = ImageUtils.cutBitmap(bmp, r,
												config);
										iv.setImageBitmap(bmp);
									}
								});
							}
						}

						@Override
						public void onImageLoad(Integer t, Drawable drawable) {

						}

						@Override
						public void onError() {

						}

						@Override
						public void onError(Integer t) {

						}
					});
			TextView title = (TextView) view.findViewById(R.id.PlayText);
			title.setText(larkObj.title);

			// info
			TextView photoValid = (TextView) view
					.findViewById(R.id.PlayAvailab);
			photoValid.setText(larkObj.validity);
			TextView photoDesc = (TextView) view.findViewById(R.id.PlayExplain);
			photoDesc.setText(larkObj.desc);
			photoDesc.setLines(5);
			photoDesc.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					displayDetailInfo(larkObj.desc);
				}
			});

			((ImageButton) view.findViewById(R.id.explain_extent))
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							displayDetailInfo(larkObj.desc);
						}
					});

			// phone number
			TextView photoNum = (TextView) view.findViewById(R.id.PlayConnect);
			if (larkObj.phone != null && larkObj.phone.length() != 0) {
				photoNum.setText(larkObj.phone);
			} else {
				((RelativeLayout) view.findViewById(R.id.layoutConnect))
						.setVisibility(View.GONE);
			}

			// address
			TextView address = (TextView) view.findViewById(R.id.PlayAddress);
			// address.setTextColor(Color.BLUE);
			address.setId(tvId);
			tvId++;
			if (larkObj.address != null && larkObj.address.length() != 0) {
				// address.setOnClickListener(new TextViewClick());
				// address.setText(Html.fromHtml("<u>" + larkObj.address +
				// "</u>"));
				address.setText(larkObj.address);
			} else {
				((RelativeLayout) view.findViewById(R.id.layoutAddress))
						.setVisibility(View.GONE);
			}

			Button btn = (Button) view.findViewById(R.id.PlayUse);
			btn.setId(btnId);
			SharedPreferences remindShared = getSharedPreferences(""
					+ larkObj.lark_id, 0);
			if (remindShared.getBoolean("isRemind", false)) {
				btn.setBackgroundResource(R.drawable.play_use_down);
				btn.setText(getResources().getString(R.string.play_used));
			} else {
				btn.setText(getResources().getString(R.string.play_use));
				btn.setOnClickListener(new ButtonClick());
			}
			if (!larkObj.is_button) {
				btn.setVisibility(View.GONE);
			}
			btnId++;
			list.add(view);
		}
	}

	private void displayDetailInfo(String textInfo) {
		InfoDialog dialog = new InfoDialog(this);
		dialog.setInverseBackgroundForced(true);
		dialog.setInformation(textInfo);
		dialog.show();
	}

	class LayoutLongClick implements OnLongClickListener {

		@Override
		public boolean onLongClick(View v) {
			for (int i = 0; i < list.size(); i++) {
				LarkObj larkObj = larkList.get(i);
				if (larkObj.lark_id == v.getId()) {
					viewpager.removeView(list.get(i));
					list.remove(i);
					viewpager.setCurrentItem(list.size() - 1 >= i ? i + 1
							: i - 1, true);
					adapter.notifyDataSetChanged();
					break;
				}
			}
			return false;
		}
	}

	class TextViewClick implements OnClickListener {
		@Override
		public void onClick(View arg0) {
			for (int i = 0; i < list.size(); i++) {
				if (textViewId + i == arg0.getId()) {
					Intent intent = new Intent();
					intent.putExtra("index", i);
					intent.putExtra("location_type",
							ScenicMapLocationActivity.STORE_LOCATION);
					intent.setClass(PlayViewPagerActivity.this,
							ScenicMapLocationActivity.class);
					startActivity(intent);
					overridePendingTransition(R.anim.push_right_translate,
							R.anim.pull_left_translate);
				}
			}
		}
	}

	class ButtonClick implements OnClickListener {
		@Override
		public void onClick(View btnView) {
			for (int i = 0; i < list.size(); i++) {
				if (buttonId + i == btnView.getId()) {
					final Button btn = (Button) btnView;
					final LarkObj larkObj = larkList.get(i);
					AlertDialog.Builder builder = new AlertDialog.Builder(
							PlayViewPagerActivity.this);
					builder.setTitle(R.string.lark_use_title);
					builder.setMessage(R.string.lark_use_message);
					builder.setPositiveButton(R.string.confirm,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int arg1) {
									SharedPreferences remindShared = getSharedPreferences(
											"" + larkObj.lark_id, 0);
									remindShared.edit()
											.putBoolean("isRemind", true)
											.commit();
									btn.setBackgroundResource(R.drawable.play_use_down);
									btn.setText(getResources().getString(
											R.string.play_used));
								}
							});
					builder.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int arg1) {
									dialog.cancel();
								}
							});
					builder.create();
					builder.show();
					break;
				}
			}
		}
	}

	class ViewPagerAdapter extends PagerAdapter {

		private ArrayList<Item> group;

		private List<View> list = null;

		public void clean(int position) {
			list.remove(position);
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		public ViewPagerAdapter(List<View> list) {
			this.list = list;
		}

		public int getCount() {
			return list.size();
		}

		private void destoryAllView(ViewGroup container) {
			container.removeAllViews();
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(list.get(position));
			return list.get(position);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(list.get(position));
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

	}

	class ViewPagerPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
		}

		@Override
		public void onPageScrolled(int page, float positionOffset,
				int positionOffsetPixels) {
		}

		@Override
		public void onPageSelected(int page) {
			for (int i = 0; i < list.size(); i++) {
				if (page == i) {
					textView.setText((page + 1) + " / " + list.size());
				} else {
				}
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			overridePendingTransition(R.anim.push_left_translate,
					R.anim.pull_right_translate);
		}
		return super.onKeyDown(keyCode, event);
	}

	public Handler mhandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			if (msg.what == 0) {

			}
		}
	};

	private class InfoDialog extends AlertDialog {

		private TextView textView = null;

		protected InfoDialog(Context context) {
			super(context);

			textView = new TextView(context);
			textView.setBackgroundColor(Color.WHITE);
			textView.setTextColor(Color.BLACK);
			textView.setText("test");
			textView.setPadding(10, 10, 10, 10);
			textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources()
					.getDimensionPixelSize(R.dimen.lark_connect_size));
			textView.setHeight(600);
			setView(textView);

			textView.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					// I want the dialog to close at this point
					dismiss();
				}
			});
		}

		public void setInformation(String textInfo) {
			textView.setText(textInfo);
		}

	}

}
